package com.zm.damai.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zm.damai.util.JwtUtil;
import com.zm.damai.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

@Slf4j
@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        //后置拦截
        return "post";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext cxt = RequestContext.getCurrentContext();
        HttpServletRequest request = cxt.getRequest();
        String servletPath = request.getServletPath();
        log.debug("servletPath",servletPath);
        return "/damai-user/sign/login".equals(servletPath) ||
                "/user/sign/login".equals(servletPath);
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext cxt = RequestContext.getCurrentContext();
        InputStream inputStream = cxt.getResponseDataStream();
        byte[] data = new byte[1024];
        try {
            int count = inputStream.read(data);
            String json = new String(data, 0, count);
            ObjectMapper objectMapper = new ObjectMapper();
            System.out.println("json = " + json);
            Result result = objectMapper.readValue(json, Result.class);
            if (result.getCode() == 1){
                //登录成功 ，用户信息编码成 jwt =》 写入响应头 Authorization
                String s = objectMapper.writeValueAsString(result.getData());
                HashMap hashMap = objectMapper.readValue(s, HashMap.class);
                String jwt = JwtUtil.createJWT(30, hashMap);
                log.debug("jwt",jwt);
                cxt.getResponse().addHeader("Authorization",jwt);
            }
            cxt.getResponse().setContentType("application/json;charset=utf-8");
            //重新将 result 写入响应对象
            cxt.setResponseBody(json);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
